package ssq.gamest.game;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import ssq.utils.Pair;

public abstract class PokerPattern implements Comparable<PokerPattern>
{
    /**
     * 保存各级权重信息, 以便同牌型的比较.
     */
    public static final LinkedList<Pair<PokerPattern, PokerCardGroup>> emptyResult = new LinkedList<Pair<PokerPattern, PokerCardGroup>>();
    public List<Integer>                                               weights;
    public int                                                         sumOfCards;
    public Poker                                                       game;
    
    public PokerPattern()
    {
    }

    @Override
    public String toString()
    {
        return getClass().getSimpleName();
    }

    public PokerPattern(Poker game, int sumOfCards, List<Integer> weights)
    {
        this.sumOfCards = sumOfCards;
        this.game = game;
        this.weights = weights;
    }
    
    /**
     * @return 1: 比o大; -1: 比o小, 0: 与o相等; -2: 无法比较大小
     */
    @Override
    public int compareTo(PokerPattern o)
    {
        Class<? extends PokerPattern> class1 = getClass(), class2 = o.getClass();
        
        if (class1.equals(class2))
        {
            if (canCompare(o))
            {
                Iterator<Integer> i1 = weights.iterator(), i2 = o.weights.iterator();
                // 权重个数肯定相同
                while (i1.hasNext())
                {
                    Integer w1 = i1.next(), w2 = i2.next();
                    if (w1 > w2)
                    {
                        return 1;
                    }
                    else if (w1 < w2)
                    {
                        return -1;
                    }
                }
                return 0;
            }
            else
            {
                return -2;
            }
        }
        else
        {
            return game.settings.getOrder(class1, class2);
        }
    }
    
    public boolean canCompare(PokerPattern o)
    {
        return true;
    }
    
    /**
     * 尝试将pokerCardGroup匹配到本牌型上
     *
     * @param pokerCardGroup
     * @return pokerCardGroup匹配本牌型后剩余的牌和对应的权重的二元组的列表
     */
    public abstract List<Pair<PokerPattern, PokerCardGroup>> match(PokerCardGroup pokerCardGroup, boolean partial, boolean first);
    
    public List<Pair<PokerPattern, PokerCardGroup>> match(PokerCardGroup pokerCardGroup)
    {
        return match(pokerCardGroup, false, false);
    }
    
    protected int getOrder(PokerOrderSettings settings, PokerCard card)
    {
        return settings.pointOrder.indexOf(card.point);
    }

    protected boolean isEmpty(LinkedList<PokerCard>[] cardGroups)
    {
        for (int i = 0; i < cardGroups.length; i++)
        {
            if (cardGroups[i] != null && !cardGroups[i].isEmpty())
                return false;
        }
        return true;
    }
}